package com.itheima.service;


import com.itheima.mapper.UserMapper;
import com.itheima.pojo.User;
import com.itheima.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;


/**
 * 登录方法
 */
public class UserService {
    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
    public User login(String username, String password){
        //2.获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //3.获取UserMapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //4.调用UserMapper的select方法
        User user = mapper.select(username, password);
        //5.关闭资源
        sqlSession.close();

        return user;
    }

    /**
     * 注册方法
     * @param username
     * @param password
     * @return
     */
    public boolean register(User user){
        //2.获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //3.获取UserMapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //判断用户名是否存在
        User u = mapper.selectByUsername(user.getUsername());
        if (u == null){
            //用户名不存在，注册
            mapper.add(user);
            //提交事务
            sqlSession.commit();
        }
        //5.关闭资源
        sqlSession.close();


        return u == null;
    }
}
